package com.jb.repair.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.acticity.TaskDetailActivity;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.dao.DBHelper;
import com.jb.repair.dao.LocalDbDao;
import com.jb.repair.model.RegularWorkModel;
import com.jb.repair.model.TaskTableModel;
import com.jb.repair.util.FileUtil;
import com.jb.repair.util.MessageUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by wp1988 on 2016/7/18 0018.
 */
public class TaskTableAdapter extends BaseAdapter {

    private List<TaskTableModel> mdata;
    private Context mcontext;
    private LayoutInflater mInflater;
    private Handler handler;
    private LocalDbDao localDbDao;
    private String taskStatus;//定期工作状态

    private static final String TAG = "TaskTableAdapter";

    public TaskTableAdapter(Context mContext, List<TaskTableModel> mdata, Handler handler, String taskStatus) {
        this.mcontext = mContext;
        this.mdata = mdata;
        this.handler = handler;
        mInflater = LayoutInflater.from(mContext);
        localDbDao = LocalDbDao.getInstance(mContext);
        this.taskStatus = taskStatus;
    }

    @Override
    public int getCount() {
        return mdata.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.layout_item_task_table, null);
            viewHolder = new ViewHolder();
            viewHolder.tvIndex = (TextView) convertView.findViewById(R.id.tv_index);
            viewHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
            viewHolder.tvStatus = (TextView) convertView.findViewById(R.id.tv_status);
            viewHolder.btnDownload = (Button) convertView.findViewById(R.id.btn_download);
            viewHolder.btnRegister = (Button) convertView.findViewById(R.id.btn_register);
            viewHolder.btnUpload = (Button) convertView.findViewById(R.id.btn_upload);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final TaskTableModel model = mdata.get(position);
        viewHolder.tvIndex.setText(position + 1 + "");//序号
        viewHolder.tvName.setText(model.MBMC);//任务表名称
        int status = 0;
        try {
            //更新status
            String path = AppConfig.REGULAR_WORK_MODEL_DIR_PATH + model.GUID + ".xlsx";
            File file = new File(path);
            if (file.exists()) {
                //获取文件最后修改时间
                Long lastModifyTime = file.lastModified();
                Log.i(TAG, "该文件上次修改时间为：" + lastModifyTime);
                try {
                    Long lastUploadTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(model.UPLOAD_TIME).getTime() + 60 * 1000;

                    Log.i(TAG, "该文件上次上传时间为：" + lastUploadTime);
                    if (lastModifyTime > lastUploadTime) {
                        //更改状态为“未上传”
                        status = 1;
                        //如果该任务已经完成，状态仍然改为“已上传”
                        if (taskStatus.equals("0700202") || taskStatus.equals("0700204"))
                            status = 2;
                    } else {
                        //更改状态为“已上传”
                        status = 2;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            } else {
                Log.i(TAG, "文件不存在");
                //更改状态为“未下载”
                status = 0;
            }
            //保存到数据库
            localDbDao.update(DBHelper.CT_TASK_MODEL_NAME, "STATUS", status + "", model.GUID);

        } catch (Exception e) {
            status = -1;
        }

        viewHolder.tvStatus.setText(status == 0 ? "未下载" : status == 1 ? "未上传" : status == 2 ? "已上传" : "未知状态");//状态
        viewHolder.tvStatus.setTextColor(status == 2 ? mcontext.getResources().getColor(R.color.green_dark) : mcontext.getResources().getColor(R.color.red));
        if (status == 1) {
            //未上传
            //模板已下载
            //下载按钮不可用
            viewHolder.btnDownload.setTag(false);
            viewHolder.btnDownload.setBackgroundColor(mcontext.getResources().getColor(R.color.gray_light));
            //填写（预览）按钮可用
            viewHolder.btnRegister.setTag(true);
            viewHolder.btnRegister.setBackgroundColor(mcontext.getResources().getColor(R.color.blue));
            //提交按钮可用
            viewHolder.btnUpload.setTag(true);
            viewHolder.btnUpload.setBackgroundColor(mcontext.getResources().getColor(R.color.blue));

        } else if (status == 0) {
            //模板未下载
            //下载按钮可用
            viewHolder.btnDownload.setTag(true);
            viewHolder.btnDownload.setBackgroundColor(mcontext.getResources().getColor(R.color.blue));
            //填写（预览）按钮不可用
            viewHolder.btnRegister.setTag(false);
            viewHolder.btnRegister.setBackgroundColor(mcontext.getResources().getColor(R.color.gray_light));
            //提交按钮不可用
            viewHolder.btnUpload.setTag(false);
            viewHolder.btnUpload.setBackgroundColor(mcontext.getResources().getColor(R.color.gray_light));
        } else if (status == 2) {
            //已上传
            //下载按钮不可用
            viewHolder.btnDownload.setTag(false);
            viewHolder.btnDownload.setBackgroundColor(mcontext.getResources().getColor(R.color.gray_light));
            //填写（预览）按钮可用
            viewHolder.btnRegister.setTag(true);
            viewHolder.btnRegister.setBackgroundColor(mcontext.getResources().getColor(R.color.blue));
            //提交按钮不可用
            viewHolder.btnUpload.setTag(false);
            viewHolder.btnUpload.setBackgroundColor(mcontext.getResources().getColor(R.color.gray_light));
        }

        //根据定期工作状态决定按钮的可见
        if (taskStatus.equals("0700202") || taskStatus.equals("0700204")) {
            //已（超期）完成，下载根据当前状态决定是否可见，提交不可见，填写（预览）按钮改为只预览
            viewHolder.btnDownload.setVisibility(status == 0 ? View.VISIBLE : View.GONE);
            viewHolder.btnRegister.setText("查看");
            viewHolder.btnUpload.setVisibility(View.GONE);
        }

        //为下载按钮添加监听
        viewHolder.btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((Boolean) view.getTag()) {
                    //下载模板
                    Message msg = new Message();
                    msg.what = TaskDetailActivity.MSG_TYPE_DOWNLOAD;
                    msg.obj = model;
                    msg.arg1 = position;
                    handler.sendMessage(msg);
                } else {
                    MessageUtil.showToast(mcontext, "已下载");
                }
            }
        });
        //为填写按钮添加监听
        viewHolder.btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((Boolean) view.getTag()) {
                    //打开模板
                    Message msg = new Message();
                    msg.what = TaskDetailActivity.MSG_TYPE_REGISTER;
                    msg.obj = AppConfig.REGULAR_WORK_MODEL_DIR_PATH + model.GUID + ".xlsx";
                    handler.sendMessage(msg);
                } else {
                    MessageUtil.showToast(mcontext, "请先下载任务表");
                }
            }
        });
        //为提交按钮添加监听
        viewHolder.btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((Boolean) view.getTag()) {
                    //上传模板
                    Message msg = new Message();
                    msg.what = TaskDetailActivity.MSG_TYPE_UPLOAD;
                    msg.obj = model;
                    msg.arg1 = position;
                    handler.sendMessage(msg);
                } else if (model.STATUS.equals("2")) {
                    MessageUtil.showToast(mcontext, "已提交");
                } else
                    MessageUtil.showToast(mcontext, "请先下载任务表");
            }
        });

        return convertView;
    }

    class ViewHolder {
        TextView tvIndex;
        TextView tvName;
        TextView tvStatus;
        Button btnDownload;
        Button btnRegister;
        Button btnUpload;
    }
}
